<template>
  <div class="login-container">
    <el-form class="login-form" ref="loginFormRef" :model="loginForm" :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { setToken } from '@/utils/token';
import type { FormInstance, FormRules } from 'element-plus';
import { reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const loginFormRef = ref<FormInstance>({});
const router = useRouter();
const route = useRoute();
const loginForm = reactive({
  username: 'admin',
  password: '123456',
});
const rules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

const login = async () => {
  await loginFormRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      if (loginForm.username == 'admin' && loginForm.password == '123456') {
        setToken('admin');
        router.push((route.query.redirect as string) ?? '/');
      } else {
        console.log('登录失败，请检查用户名和密码');
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
</script>

<style lang="scss" scoped>
.login-container {
  @include flex-center();
  height: 100vh;
}
</style>
